package com.zmy.xcx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zmy.xcx.context.WxUserContext;
import com.zmy.xcx.dao.entity.HypertensionMedication;
import com.zmy.xcx.dao.entity.HypertensionSelfCheck;
import com.zmy.xcx.dao.entity.NonDrugTreatment;
import com.zmy.xcx.dao.mapper.HypertensionMedicationMapper;
import com.zmy.xcx.dao.mapper.HypertensionSelfCheckMapper;
import com.zmy.xcx.pojo.dto.HypertensionSelfCheckDTO;
import com.zmy.xcx.pojo.vo.AdviceVO;
import com.zmy.xcx.pojo.vo.HypertensionMedicationVO;
import com.zmy.xcx.pojo.vo.HypertensionSelfCheckVO;
import com.zmy.xcx.service.HypertensionSelfCheckService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class HypertensionSelfCheckServiceImpl extends ServiceImpl<HypertensionSelfCheckMapper, HypertensionSelfCheck> implements HypertensionSelfCheckService {
    private final HypertensionMedicationMapper hypertensionMedicationMapper;
    @Override
    public void saveAgeCheckHypertension(Integer age) {
        //获取openid
        String currentOpenid = WxUserContext.getCurrentOpenid();
        HypertensionSelfCheck hypertensionSelfCheck = lambdaQuery().eq(HypertensionSelfCheck::getOpenid, currentOpenid).one();
        //判断是否存在
        if (hypertensionSelfCheck == null) {
            //不存在就插入
            hypertensionSelfCheck = new HypertensionSelfCheck().builder()
                    .openid(currentOpenid)
                    .age(age)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            save(hypertensionSelfCheck);

        }
        //存在就更新
        //update 表 set age = #{age} where openid = #{openid}
        lambdaUpdate().eq(HypertensionSelfCheck::getOpenid, currentOpenid)
                .set(HypertensionSelfCheck::getAge, age).update();

    }

    /**
     * 保存用户输入信息
     * @param hypertensionSelfCheckDTO
     * @return
     */
    @Transactional
    @Override
    public List<AdviceVO> saveCheckHypertension(HypertensionSelfCheckDTO hypertensionSelfCheckDTO) {
        String currentOpenid = WxUserContext.getCurrentOpenid();
        //1.更新用户信息
        HypertensionSelfCheck hypertensionSelfCheck = BeanUtil.copyProperties(hypertensionSelfCheckDTO, HypertensionSelfCheck.class);
        hypertensionSelfCheck.setUpdateTime(LocalDateTime.now());
        
        // 检查用户记录是否存在
        HypertensionSelfCheck existingCheck = lambdaQuery()
                .eq(HypertensionSelfCheck::getOpenid, currentOpenid)
                .eq(HypertensionSelfCheck::getDelFlag, 0)
                .one();
                
        if (existingCheck == null) {
            // 如果记录不存在，创建新记录
            hypertensionSelfCheck.setOpenid(currentOpenid);
            hypertensionSelfCheck.setCreateTime(LocalDateTime.now());
            save(hypertensionSelfCheck);
        } else {
            // 如果记录存在，更新记录
            LambdaUpdateWrapper<HypertensionSelfCheck> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(HypertensionSelfCheck::getOpenid, currentOpenid)
                    .eq(HypertensionSelfCheck::getDelFlag, 0);
            update(hypertensionSelfCheck, lambdaUpdateWrapper);
        }

        //2.根据用户返回建议
        //2.1年龄段针对性建议
        List<AdviceVO> list = new ArrayList<>();
        if (hypertensionSelfCheckDTO.getAgeGroup() == 0) {
            //0代表血压自测表的儿童，0代表非药物治疗的成人   (自测表0对应非药物治疗方案的1)
            list.add(getAdvice(1));
        } else {
            //1,2代表血压自测表的成年人及老年人，对应非药物治疗的0   (自测表1,2对应非药物治疗方案的0)
            list.add(getAdvice(0));
        }
        
        //3.1根据用户信息的自检详情内容返回 危险因素的建议
        //获取用户危险因素内容map
        Map<String, String> checkDetails = hypertensionSelfCheck.getCheckDetails();
        log.info("用户自检详情内容:{}", checkDetails);
        
        //获取表中的危险因素的条件
        List<NonDrugTreatment> treatmentList = Db.lambdaQuery(NonDrugTreatment.class)
                                                 .eq(NonDrugTreatment::getAgeGroup, 2)
                                                 .list();
        List<String> collectRiskFactor = treatmentList.stream()
                                                     .map(NonDrugTreatment::getRiskFactor)
                                                     .collect(Collectors.toList());
        
        //3.2根据用户信息的自检详情内容返回 危险因素的建议
        // 检查checkDetails是否为null
        if (checkDetails != null) {
            for(String c : collectRiskFactor) {
                //匹配
                if(checkDetails.containsKey(c)) {
                    //匹配成功，获取建议内容
                    NonDrugTreatment nonDrugTreatment = Db.lambdaQuery(NonDrugTreatment.class)
                                                         .eq(NonDrugTreatment::getRiskFactor, c)
                                                         .one();
                    AdviceVO adviceVO = new AdviceVO();
                    adviceVO.setType("危险因素"+ c + "建议");
                    adviceVO.setContent(nonDrugTreatment.getRecommendation());
                    //添加到list
                    list.add(adviceVO);
                }
            }
        }

        return list;
    }

    @Override
    public HypertensionSelfCheckVO getHistoryHypertension() {
        String currentOpenid = WxUserContext.getCurrentOpenid();
        //根据openid查询
        HypertensionSelfCheck hypertensionSelfCheck = lambdaQuery().eq(HypertensionSelfCheck::getOpenid, currentOpenid).one();
        HypertensionSelfCheckVO hypertensionSelfCheckVO = BeanUtil.copyProperties(hypertensionSelfCheck, HypertensionSelfCheckVO.class);
        return hypertensionSelfCheckVO;
    }

    /**
     * 获取药品
     * @return
     */
    @Override
    public List<HypertensionMedicationVO> getMedicine() {
        List<HypertensionMedication> list =  hypertensionMedicationMapper.getMedicineList();
        ArrayList<HypertensionMedicationVO> listVO = new ArrayList<>();
        list.forEach(hypertensionMedication -> {
            HypertensionMedicationVO hypertensionMedicationVO =BeanUtil.copyProperties(hypertensionMedication, HypertensionMedicationVO.class);
            listVO.add(hypertensionMedicationVO);
        });
        return listVO;
    }

    /**
     * 增加点击量
     * @param id
     */
    @Override
    public void addClicks(Integer id) {
        //更新
        hypertensionMedicationMapper.updateClicksById(id);
    }

    //获取对应年龄段的建议方法
    private AdviceVO getAdvice(int i){
        //获取建议content
        NonDrugTreatment nonDrugTreatment = Db.lambdaQuery(NonDrugTreatment.class).eq(NonDrugTreatment::getAgeGroup, i).one();
        //将建议内容封装到AdviceVO中
        AdviceVO adviceVO = new AdviceVO();
        adviceVO.setType("年龄段建议");
        log.info("年龄段内容{}",nonDrugTreatment.getRecommendation());
        adviceVO.setContent(nonDrugTreatment.getRecommendation());
        return adviceVO;
    }
}
